
import "./index.less"
import { Space, Table, Tag, Input, Button, message, TablePaginationConfig, Modal, Form, Select, InputNumber, Upload } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import { getOrderList, handlerOrder } from "@/api/order"
import { useEffect, useRef, useState } from "react";
import { applyServe } from "@/api/server"
import systme from "@/api/constant"
import type { UploadFile } from 'antd/es/upload/interface';
import type { UploadProps } from 'antd/es/upload';


interface orderType {
    "count": number,
    "id": string,
    "orderNo": string,
    "orderTime": string,
    "pageIndex": number,
    "pageSize": number,
    "productId": string,
    "productName": string,
    "status": number,
    "total": number,
    "userId": string,
    "userName": string
}

let userId = JSON.parse(sessionStorage.getItem("user") as string).id
let userName = JSON.parse(sessionStorage.getItem("user") as string).userName
let searchValue = {
    userId: userId,
    orderNo: '',
    pageIndex: 1,
    pageSize: 10
}

const { TextArea } = Input;


const formateStatus = (status: number) => {
    let statusCN = ['待发货', '运输中', '已签收']

    return statusCN[status]
}

let orderId: string;
let orderNo:string;

export default function MyOrder() {

    const initSearchData = () => {
        searchValue = {
            userId: userId,
            orderNo: '',
            pageIndex: 1,
            pageSize: 10
        }
    }
    const handlerSearch = (e: any) => {
        searchValue.orderNo = e.target.value
    }
    const search = () => {
        searchValue.pageIndex = 1
        initOrderList()
    }


    const [loading, setLoading] = useState(true)
    const columns: ColumnsType<orderType> = [
        {
            title: '订单号',
            dataIndex: 'orderNo',
            key: 'orderNo',
        },

        {
            title: '下单时间',
            key: 'orderTime',
            render: (_, record: orderType) => (
                <Space size="middle">
                    <div>
                        {record.orderTime.slice(0, 10)}
                    </div>
                </Space>
            )
        },
        {
            title: '状态',
            key: 'status',
            render: (_, record: orderType) => (
                <div>
                    {formateStatus(record.status)}
                </div>
            ),
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record: orderType) => (
                <Space size="middle">
                    {record.status == 1 && <a onClick={() => { updateOrder(2, record.id) }} >签收</a>}
                    {record.status == 2 && <a onClick={() => { applyServer(record) }} >申请服务</a>}
                </Space>
            ),
        },
    ];
    const applyServer = (record: orderType) => {
        setFileList([])
        showModal()
        orderId = record.id,
        orderNo = record.orderNo
    }
    const updateOrder = (e: number, id: string) => {
        handlerOrder({ id, status: e }).then((res) => {
            if (res.code == 200) {
                message.success("处理成功")
                initOrderList()
            } else {
                message.error(res.msg || systme.ERROR_MESSAGE)
            }
        }).catch((err) => {
            message.error(systme.ERROR_ACTION)
        })
    }


    const [data, setData] = useState<orderType[]>([])
    const PageChange = (page: number, pageSize: number) => {
        searchValue.pageIndex = page
        searchValue.pageSize = pageSize
        setLoading(true)
        setConfig({ ...saveValue.current, pageSize, current: page })
        initOrderList()
    }

    const initOrderList = (data = searchValue) => {
        getOrderList(data).then((res) => {
            if (res.code == 200) {
                setData(res.data.list)
                setConfig({ ...saveValue.current, total: res.data.total })
            } else {
                message.error(res.msg || systme.ERROR_MESSAGE)
            }
            setLoading(false)
        }).catch((error) => {
            message.error(error || systme.ERROR_MESSAGE)
            setLoading(false)
        })
    }

    let pageConfig: TablePaginationConfig = {
        position: ['bottomCenter'],
        total: 0,
        showTotal: (total: number) => `共 ${total} 条`,
        pageSizeOptions: [10, 20, 30, 40, 50],
        showSizeChanger: true,
        showQuickJumper: true,
        onChange: PageChange,
        pageSize: 10,
        current: 1

    }
    let [config, setConfig] = useState((pageConfig))
    let saveValue = useRef<TablePaginationConfig>()
    useEffect(() => {
        //储存数据
        saveValue.current = config
    }, [config])

    useEffect(() => {
        initSearchData()
        initOrderList()
    }, [])

    const [isModalOpen, setIsModalOpen] = useState(false);

    const showModal = () => {
        form.resetFields()
        setIsModalOpen(true);

    };

    const handleOk = () => {
        form.validateFields().then((values) => {
            console.log(values);
            if (values.imgs.file.response.code != 200) {
                message.error("图片上传失败")
                return
            }
            let params = {
                content: values.content,
                images: values.imgs.file.response.data,
                orderId,
                userId,
                userName,
                status: 0,
                orderNo,
            }
            applyServe(params).then((res) => {
                if (res.code == 200) {
                    message.success("申请成功")
                    setIsModalOpen(false)
                    initOrderList()
                } else {
                    message.error(res.msg || systme.ERROR_MESSAGE)
                }
            }).catch(err => {
                message.error(systme.ERROR_MESSAGE)
            })

        }).catch((err) => {
            message.error(systme.ERROR_MESSAGE)
        })

    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const [form] = Form.useForm();

    const [fileList, setFileList] = useState<UploadFile[]>([])

    const handleChange: UploadProps['onChange'] = ({ file: newFile, fileList: newFileList }) => {
        setFileList(newFileList)
    };

    const handlePreview = (file: UploadFile) => {
        setpriewImg(file.thumbUrl as string || file.url as string)
        setIsModalOpen2(true)
    };

    const uploadButton = (
        <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );

    const [isModalOpen2, setIsModalOpen2] = useState<boolean>(false)
    const [priewImg, setpriewImg] = useState<string>('')


    return (
        <div className="box_views">
            <div className="header flex">
                <div className="header_search flex">
                    <div className="item">
                        <Input placeholder="请输入订单编号" allowClear onChange={(e: unknown) => { handlerSearch(e) }} />
                    </div>
                    <Button type="primary" icon={<SearchOutlined />} size="middle" onClick={search}>查询</Button>
                </div>
            </div>
            <Table columns={columns} dataSource={data} pagination={config} rowKey={item => item.id} loading={loading} />
            <Modal title="服务申请" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} width={800} okText="提交" >
                <Form
                    name="basic"
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                    style={{ width: 700 }}
                    form={form}
                >
                    <Form.Item
                        label="问题截图"
                        name="imgs"
                    >
                        <Upload
                            action={`${import.meta.env.VITE_APP_BASE_URL}pro/upload`}
                            listType="picture-card"
                            fileList={fileList}
                            onChange={handleChange}
                            onPreview={handlePreview}
                            name={'uploadFile'}
                        >
                            {fileList.length >= 1 ? null : uploadButton}
                        </Upload>
                    </Form.Item>
                    <Form.Item
                        label="问题描述"
                        name="content"
                        rules={[{ required: true, message: '请输入价格' }]}
                    >
                        <TextArea rows={4} placeholder="请输入你对产品问题的描述" />
                    </Form.Item>
                </Form>
            </Modal>
            <Modal title="预览图" open={isModalOpen2} onOk={() => setIsModalOpen2(false)} onCancel={() => setIsModalOpen2(false)} width={800}>
                <img src={priewImg} alt="" style={{ width: "100%", height: "800px" }} />
            </Modal>
        </div>
    )
}